#include "glwidget.h"

#include <QGLShader>
#include <QDebug>

GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
}

void GLWidget::initializeGL()
{
    const char *vShaderStr =
            "attribute vec4 vPosition;\n"
            "void main()\n"
            "{\n"
            "    gl_Position = vPosition;\n"
            "}\n";
    const char *fShaderStr =
            "mediump float;\n"
            "void main()\n"
            "{\n"
            "    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
            "}\n";
    loadShader(GL_VERTEX_SHADER, vShaderStr);
    loadShader(GL_FRAGMENT_SHADER, fShaderStr);
    program.bindAttributeLocation("vPosition", 0);
    if (!program.link())
    {
        qWarning() << program.log();
        program.removeAllShaders();
        return;
    }
    glClearColor(0.0f, 0.0f, 0.0f, 1.0);
}

void GLWidget::paintGL()
{
    GLfloat vertices[] = {
        0.0f, 0.5f, 0.0f,
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f
    };
    glViewport(0, 0, width(), height());
    glClear(GL_COLOR_BUFFER_BIT);
    program.bind();
    program.setAttributeArray(0, GL_FLOAT, vertices, 3);
    program.enableAttributeArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
}

void GLWidget::resizeGL(int width, int height)
{
    (void)width;
    (void)height;
}

void GLWidget::loadShader(GLenum type, const QByteArray &shaderSrc)
{
    QGLShader::ShaderType shaderType;
    switch(type)
    {
    case GL_VERTEX_SHADER :
        shaderType = QGLShader::Vertex;
        break;
    case GL_FRAGMENT_SHADER :
        shaderType = QGLShader::Fragment;
        break;
    default :
        qWarning() << "invalid shader type " << type;
        break;
    }

    QGLShader *shader = new QGLShader(shaderType, this);
    if (!shader->compileSourceCode(shaderSrc))
    {
        qWarning() << shader->log();
    }
    program.addShader(shader);
}
